package csx.study.demo.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;


//订单id是要发送给用户的，id自增长会有明显规律
//考虑3种方案，redis自增长/uuid/雪花算法
//雪花算法用的最多
//TODO 用雪花算法
/**
 * redis自增
 */
@Component
public class RedisIdWorker {

    //初始时间错
    private static final Long BEGIN_TIMESTAMP = 1640995200L;

    //序列号位数
    private static final Integer COUNT_BITS = 32;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public Long nextId(String keyPrefix) {
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        //生成序列号
        //生成当前日期 精确到天
        String today = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        //自增长
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + today);
        //拼接并返回
        return timestamp << COUNT_BITS|count ;
    }

}
